import router from '@/router/index'
import { get } from 'js-cookie'
import store from '@/store/index'

const whiteList = ['/login', '/register']

router.beforeEach(async(to, from, next) => {
  const hasToken = get('token')
  if (hasToken) {
    if (to.path === '/login' || to.path === '/register') {
      next({ path: '/' })
    } else {
      const roles = JSON.parse(localStorage.getItem('userinfo')).identify || ''
      const hasRoutes = store.getters.roles && store.getters.roles.length > 0
      if (hasRoutes) {
        next()
      } else {
        try {
          const accessedRoutes = await store.dispatch('permission/generateRoutes', roles)
          router.options.routes = accessedRoutes
          router.addRoutes(accessedRoutes)
          if ((from.path === '/' || from.path === '/login') && to.path === '/404') {
            next({ path: '/home', replace: true })
          } else {
            next({ ...to, replace: true })
          }
        } catch (error) {
          await store.dispatch('user/resetToken')
          next(`/login?redirect=${to.path}`)
        }
      }
    }
  } else {
    if (whiteList.indexOf(to.path) !== -1) {
      next()
    } else {
      next(`/login?redirect=/home`)
    }
  }
  next()
})
